import asyncio
from bleak import BleakScanner
import pandas as pd
import os
import time
from collections import defaultdict

# 存储扫描结果的字典
scan_data = defaultdict(list)

# 目标设备名称列表
TARGET_DEVICES = ['R25050901','R25050913','R25040204']


def detection_callback(device, advertisement_data):
    print("_______________________________")
    if device.name in TARGET_DEVICES:  # 检查是否为目标设备
        # 为每个设备记录RSSI值
        scan_data[device.name].append(advertisement_data.rssi)
        # 实时打印发现信息
        print(f"发现设备: {device.name}, RSSI: {advertisement_data.rssi} dBm")

async def scan_ble_devices():
    # 设置扫描持续时间（单位：秒）
    scan_duration = 600
    end_time = time.time() + scan_duration
    # 使用 detection_callback 方式扫描

    scanner = BleakScanner(detection_callback=detection_callback)
    await scanner.start()

    try:
        while time.time() < end_time:
            await asyncio.sleep(1)  # 降低CPU占用
    finally:
        await scanner.stop()

    # 创建DataFrame - 确保所有列长度相同
    max_length = max((len(scan_data.get(device, [])) for device in TARGET_DEVICES), default=0)
    data = {}
    for device in TARGET_DEVICES:
        rssi_list = scan_data.get(device, [])
        # 填充NaN使所有列等长
        if len(rssi_list) < max_length:
            rssi_list += [None] * (max_length - len(rssi_list))
        data[f'{device}_RSSI(dBm)'] = rssi_list

    df = pd.DataFrame(data)

    # 保存到桌面
    desktop_path = os.path.join(os.path.expanduser("~"), "Desktop")
    excel_file = os.path.join(desktop_path, "3m.xlsx")

    df.to_excel(excel_file, index=False)

    # 打印统计信息
    print("\n扫描完成！结果已保存到：", excel_file)
    print("\n各设备发现次数统计：")
    for device in TARGET_DEVICES:
        count = len(scan_data.get(device, []))  # 使用原始数据统计实际检测次数
        print(f"{device}: {count}次")


# 运行扫描
asyncio.run(scan_ble_devices())